package com.contain2;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;

import com.contain2.abstractcontain.demo1.Countries;

/**
 * 生成只读容器
 * 
 * @author Administrator
 *
 */
public class ReadOnly {

	private static Collection<String> data = new ArrayList<String>();
	private static Map<String, String> datam = new HashMap<String, String>();

	public static void main(String[] args) {
		// 在把容器设为只读之前，必须填入有意义的数据，装载后，就应该用“不可改变的”方法返回的引用去替换掉原来的引用
		for (int i = 0; i < Countries.DATA.length; i++) {
			data.add(Countries.DATA[i][0]);
		}
		for (int i = 0; i < Countries.DATA.length; i++) {
			datam.put(Countries.DATA[i][0], Countries.DATA[i][1]);
		}

		try {
			// 可以保留一份了修改的容器，作为类的私有成员，然后通过方法调用返回对该容器的只读的引用，这样一来，就只有你可以修改容器的内容，别人只能读取
			Collection<String> c = Collections
					.unmodifiableCollection(new ArrayList(data));
			System.out.println(c);
			c.add("one");
		} catch (UnsupportedOperationException e) {
			e.printStackTrace();
		}

		try {
			List<String> a = Collections.unmodifiableList(new ArrayList(data));
			ListIterator<String> lit = a.listIterator();
			System.out.println(lit.next());
			lit.add("one");
		} catch (UnsupportedOperationException e) {
			e.printStackTrace();
		}

		Set<String> ss = Collections.unmodifiableSet(new TreeSet<String>(data));

		try {
			Map<String, String> m = Collections
					.unmodifiableMap(new HashMap<String, String>(datam));
			System.out.println(m);
			m.put("Ralph", "Howdy");
		} catch (UnsupportedOperationException e) {
			e.printStackTrace();
		}

		Map<String, String> sm = Collections
				.unmodifiableSortedMap(new TreeMap<String, String>(datam));
	}

}
